package com.example.weixinsystem.config;

import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.weixin.common.core.domain.Result;
import com.weixin.common.core.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * @version 1.0.0
 * @className: GloableExeception
 * @description: 微信系统服务异常全局处理
 * @author: zhangjunfa
 * @date: 2023/5/27 12:00
 */
@Slf4j
@RestControllerAdvice
public class GlobalException {
    /**
     * 数据绑定异常
     *
     * @param be
     * @param request
     * @return
     */
    @ExceptionHandler(BindException.class)
    public Result<?> handlerBindException(BindException be, HttpServletRequest request) {
        String message = be.getAllErrors().get(0).getDefaultMessage();
        String uri = request.getRequestURI();
        String method = request.getMethod();
        log.error("请求地址：{}，方法名：{},数据绑定验证发生异常:{}", uri, method, message);
        return Result.fail(message);
    }

    /**
     * 数据查询异常-Mybatis-Plus异常
     *
     * @param be
     * @param request
     * @return
     */
    @ExceptionHandler(MybatisPlusException.class)
    public Result<?> handlerMybatisPlusException(MybatisPlusException be, HttpServletRequest request) {
        String uri = request.getRequestURI();
        String method = request.getMethod();
        log.error("请求地址：{}，方法名：{},Mybatis-plus发生异常:{}", uri, method, be.getMessage());
        return Result.fail("数据库查询异常！");
    }

    /**
     * 微信服务顶级异常
     *
     * @param be
     * @param request
     * @return
     */
    @ExceptionHandler(BaseException.class)
    public Result<?> handlerBaseException(BaseException be, HttpServletRequest request) {
        String uri = request.getRequestURI();
        String method = request.getMethod();
        log.error("请求地址：{}，方法名：{},微信服务异常:{}", uri, method, be.getMessage());
        return Result.fail(be.getMessage());
    }

    /**
     * 系统异常
     *
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(Exception.class)
    public Result<?> handlerException(Exception e, HttpServletRequest request) {
        String uri = request.getRequestURI();
        String method = request.getMethod();
        log.error("请求地址：'{}',方法名：{},发生系统异常:{}", uri, method, e.getMessage());
        return Result.fail(e.getMessage());
    }
}
